import { defineStore } from 'pinia'
import type { User } from '~/types'

export const useUserStore = defineStore('user', () => {
  const user = ref<User | null>(null)

  // 获取用户信息
  async function fetchUserInfo() {
    try {
      const { data } = await $fetch<User>('/api/user/info') as any
      user.value = data
      return user.value
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return null
    }
  }

  // 更新用户信息
  async function updateUserInfo(form: Partial<User>) {
    try {
      const { data } = await $fetch<User>('/api/user/update', {
        method: 'PUT',
        body: form,
      }) as any
      user.value = data
      return { success: true }
    } catch (error: any) {
      return { success: false, message: error.message }
    }
  }

  // 上传头像
  async function uploadAvatar(file: File) {
    try {
      const formData = new FormData()
      formData.append('avatar', file)

      const { data } = await $fetch<{ url: string }>('/api/user/avatar', {
        method: 'POST',
        body: formData,
      }) as any

      if (user.value) {
        user.value.avatar = data.url
      }

      return { success: true, url: data.url }
    } catch (error: any) {
      return { success: false, message: error.message }
    }
  }

  function $reset() {
    user.value = null
  }

  return {
    user,
    fetchUserInfo,
    updateUserInfo,
    uploadAvatar,
    $reset,
  }
})